package cn.slf.ph.servlet;

import cn.slf.ph.dao.GoodsDao;
import cn.slf.ph.dao.impl.GoodsDaoImpl;
import cn.slf.ph.entity.Goods;
import cn.slf.ph.util.Result;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        //连接数据库
        GoodsDao goodsDao=new GoodsDaoImpl();
        if ("selectAll".equals(action)){
            String pageNum = req.getParameter("pageNum");
            String pageSize = req.getParameter("pageSize");
            String goodsName = req.getParameter("goodsName");
            String shopName = req.getParameter("shopName");
            String startTime = req.getParameter("startTime");
            String endTime = req.getParameter("endTime");
            String goodsStatus = req.getParameter("goodsStatus");
            //封装键值对
            Map<String,String> map=new HashMap<>();
            map.put("pageNum",pageNum);
            map.put("pageSize",pageSize);
            map.put("goodsName",goodsName);
            map.put("shopName",shopName);
            map.put("startTime",startTime);
            map.put("endTime",endTime);
            map.put("goodsStatus",goodsStatus);
            List<Goods> list=goodsDao.selectAll(map);
            int total=goodsDao.getTotal(map);

            //给出响应
            Map res=new HashMap();
            res.put("list",list);
            res.put("total",total);
            Result success = Result.success(res);
            resp.getWriter().write(JSON.toJSONString(success));
        }else if ("modifysGoodsStatus".equals(action)){
            String goodsId = req.getParameter("goodsId");
            String goodsStatus = req.getParameter("goodsStatus");
            Map<String,String> map=new HashMap<>();
            map.put("goodsId",goodsId);
            map.put("goodsStatus",goodsStatus);
            //连接数据库
            int num=goodsDao.ModifyGoodsStatus(map);
            Result success=null;
            if (num!=0){
                 success = Result.success("修改成功");
            }else {
                success = Result.error("修改失败");
            }
            //给出响应
            resp.getWriter().write(JSON.toJSONString(success));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
